/*
 * Copyright (c) 田梓萱 2021-2022.
 * All Rights Reserved.
 * All codes are protected by China's regulations on the protection of computer software, and infringement must be investigated.
 * 版权所有 (c) 田梓萱 2021-2022.
 * 所有代码均受中国《计算机软件保护条例》保护，本项目已获得软著.
 */

package com.xcl.calculator.slice.DanWeiCal;

import com.huawei.agconnect.crash.AGConnectCrash;
import com.xcl.calculator.Dialog.MyToastDialog;
import com.xcl.calculator.Preference_RW;
import com.xcl.calculator.ResourceTable;
import com.xcl.calculator.XLog;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Picker;
import ohos.agp.components.Text;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.service.WindowManager;
import ohos.data.distributed.common.KvManagerConfig;
import ohos.data.distributed.common.KvManagerFactory;
import ohos.distributedhardware.devicemanager.DeviceInfo;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.multimodalinput.event.KeyEvent;
import ohos.multimodalinput.event.MmiPoint;
import ohos.multimodalinput.event.TouchEvent;
import ohos.utils.PacMap;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

import static com.xcl.calculator.MyApplication.instance_hi;
import static java.util.regex.Pattern.compile;

/**
 * The type Dwzh 1 ability slice.
 *
 * @author Xcl
 * @date 2022 /1/16
 * @package com.xcl.calculator.slice.DanWeiCal
 */
public class DWZH1AbilitySlice extends AbilitySlice implements Component.TouchEventListener {
    /**
     * The constant label.
     */
    private static final HiLogLabel label = new HiLogLabel(HiLog.LOG_APP, 0x00234, "DWZH1AbilitySlice");
    /**
     * The constant dw1.
     */
    private static int dw1 = -1;
    /**
     * The constant dw2.
     */
    private static int dw2 = -1;
    /**
     * The constant panduan.
     */
    private static int panduan = 0;
    /**
     * The String title.
     */
    private final String[] stringTitle = {
            "公里(km)"
            , "米(m)"
            , "分米(dm)"
            , "厘米(cm)"
            , "毫米(mm)"
            , "丝(dmm)"
            , "微米(um)"
            , "里"
            , "丈"
            , "尺"
            , "寸"
            , "分"
            , "厘"
            , "海里(nmi)"
            , "英寻"
            , "英里(mi)"
            , "弗隆(fur)"
            , "码(yd)"
            , "英尺(ft)"
            , "英寸(in)"
            , "纳米(nm)"};
    /**
     * The Dw.
     */
    private int dw = -1;
    /**
     * The Starx.
     */
    private float starx;
    /**
     * The Stary.
     */
    private float stary;
    /**
     * The Endx.
     */
    private float endx;
    /**
     * The Endy.
     */
    private float endy;

    /**
     * 计算
     *
     * @param text the text
     * @return string string
     */
    private static String dwcal(String text) {
        String answer = null;
        try {
            if (isDecimal(text)) if (dw1 == -1 || dw2 == -1) {
                if (dw1 == -1) answer = "未选择原数据单位!";
                if (dw2 == -1) answer = "未选择转换后单位!";
                if (dw1 == -1 && dw2 == -1) answer = "未选择转换前后的单位!";
            } else if (dw1 == dw2) answer = text;
            else {
                double question = Double.parseDouble(text);
                switch (dw1) {
                    case 0:
                        answer = dwcal1(question);
                        break;
                    case 1:
                        answer = dwcal1(question / 1000.0);
                        break;
                    case 2:
                        answer = dwcal1(question / 10000.0);
                        break;
                    case 3:
                        answer = dwcal1(question / 100000.0);
                        break;
                    case 4:
                        answer = dwcal1(question / 1000000.0);
                        break;
                    case 5:
                        answer = dwcal1(question / 100000000.0);
                        break;
                    case 6:
                        answer = dwcal1(question / 1000000000.0);
                        break;
                    case 7:
                        answer = dwcal1(question / 2.0);
                        break;
                    case 8:
                        answer = dwcal1(question / 300.0);
                        break;
                    case 9:
                        answer = dwcal1(question / 3000.0);
                        break;
                    case 10:
                        answer = dwcal1(question / 30000.0);
                        break;
                    case 11:
                        answer = dwcal1(question / 300000.0);
                        break;
                    case 12:
                        answer = dwcal1(question / 3000000.0);
                        break;
                    case 13:
                        answer = dwcal1(question * 1852.0 / 1000);
                        break;
                    case 14:
                        answer = dwcal1(question * 0.3048 / 1000 * 6);
                        break;
                    case 15:
                        answer = dwcal1(question * 0.3048 / 1000 * 5280);
                        break;
                    case 16:
                        answer = dwcal1(question * 0.3048 / 1000 * 660);
                        break;
                    case 17:
                        answer = dwcal1(question * 0.3048 / 1000 * 3);
                        break;
                    case 18:
                        answer = dwcal1(question * 0.3048 / 1000);
                        break;
                    case 19:
                        answer = dwcal1(question * 0.3048 / 1000 / 12);
                        break;
                    case 20:
                        answer = dwcal1(question / 1000000000000.0);
                        break;
                }
            }
            else answer = "输入数据有误!";
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
        return answer;
    }

    /**
     * 计算1
     *
     * @param question the question
     * @return string string
     */
    private static String dwcal1(double question) {
        String answer = null;
        try {
            switch (dw2) {
                case 0:
                    answer = String.valueOf(question);
                    break;
                case 1:
                    answer = String.valueOf(question * 1000.0);
                    break;
                case 2:
                    answer = String.valueOf(question * 10000.0);
                    break;
                case 3:
                    answer = String.valueOf(question * 100000.0);
                    break;
                case 4:
                    answer = String.valueOf(question * 1000000.0);
                    break;
                case 5:
                    answer = String.valueOf(question * 100000000.0);
                    break;
                case 6:
                    answer = String.valueOf(question * 1000000000.0);
                    break;
                case 7:
                    answer = String.valueOf(question * 2.0);
                    break;
                case 8:
                    answer = String.valueOf(question * 300.0);
                    break;
                case 9:
                    answer = String.valueOf(question * 3000.0);
                    break;
                case 10:
                    answer = String.valueOf(question * 30000.0);
                    break;
                case 11:
                    answer = String.valueOf(question * 300000.0);
                    break;
                case 12:
                    answer = String.valueOf(question * 3000000.0);
                    break;
                case 13:
                    answer = String.valueOf(question / 1852.0 * 1000);
                    break;
                case 14:
                    answer = String.valueOf(question / 0.3048 * 1000 / 6);
                    break;
                case 15:
                    answer = String.valueOf(question / 0.3048 * 1000 / 5280);
                    break;
                case 16:
                    answer = String.valueOf(question / 0.3048 * 1000 / 660);
                    break;
                case 17:
                    answer = String.valueOf(question / 0.3048 * 1000 / 3);
                    break;
                case 18:
                    answer = String.valueOf(question / 0.3048 * 1000);
                    break;
                case 19:
                    answer = String.valueOf(question / 0.3048 * 1000 * 12);
                    break;
                case 20:
                    answer = String.valueOf(question * 1000000000000.0);
                    break;
            }
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
        return answer;
    }

    /**
     * 判断是否为小数
     *
     * @param que the que
     * @return boolean boolean
     */
    private static boolean isDecimal(String que) {
        Pattern pattern = compile("[0-9]*");
        if (que.indexOf(".") > 0) if (que.indexOf(".") == que.lastIndexOf(".") && que.split("\\.").length == 2)
            return pattern.matcher(que.replace(".", "")).matches();
        else return false;
        else return pattern.matcher(que).matches();
    }

    /**
     * 开始
     *
     * @param intent the intent
     */
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        try {
            XLog.pd_pd = Preference_RW.ff7_r();
            this.getWindow().addFlags(WindowManager.LayoutConfig.MARK_ALLOW_EXTEND_LAYOUT);
            ohos.data.distributed.device.DeviceInfo localDeviceInfo = KvManagerFactory.getInstance()
                    .createKvManager(new KvManagerConfig((this))).getLocalDeviceInfo();
            int localDeviceType = Integer.parseInt(localDeviceInfo.getType());
            if (localDeviceType == DeviceInfo.DeviceType.PHONE.value()) {
                this.setUIContent(ResourceTable.Layout_dwzhm);
                XLog.info(label, "当前设备类型为手机");
            } else if (localDeviceType == DeviceInfo.DeviceType.TABLET.value()) {
                this.setUIContent(ResourceTable.Layout_dwzht);
                XLog.info(label, "当前设备类型为平板");
            } else {
                XLog.warn(label, "暂不支持您的设备:(" + localDeviceInfo.getType() + ")");
                this.terminateAbility();
            }

            Text xinxi = (Text) DWZH1AbilitySlice.this.findComponentById(ResourceTable.Id_danwei);
            xinxi.setText("长度单位");
            Text xinxi1 = (Text) DWZH1AbilitySlice.this.findComponentById(ResourceTable.Id_botton_xinxi);
            xinxi1.setText("1/5");
            this.findComponentById(ResourceTable.Id_show0).setTouchEventListener(this);
            this.prepareButtons();
            Picker picker = (Picker) this.findComponentById(ResourceTable.Id_dw_picker);
            picker.setBindStateChangedListener(new Component.BindStateChangedListener() {
                @Override
                public void onComponentBoundToWindow(Component component) {
                    component.setTouchFocusable(true);
                    component.setVibrationEffectEnabled(true);
                    component.requestFocus();
                }

                @Override
                public void onComponentUnboundFromWindow(Component component) {
                }
            });

            picker.setMinValue(0);
            picker.setMaxValue(this.stringTitle.length - 1);
            picker.setFormatter(new Picker.Formatter() {
                @Override
                public String format(int i) {
                    return DWZH1AbilitySlice.this.stringTitle[i];
                }
            });

            picker.setValueChangedListener(new Picker.ValueChangedListener() {
                @Override
                public void onValueChanged(Picker picker, int i, int i1) {
                    DWZH1AbilitySlice.this.dw = i1;
                }
            });
            this.findComponentById(ResourceTable.Id_jback_button).setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component v) {
                    Text question = (Text) DWZH1AbilitySlice.this.findComponentById(ResourceTable.Id_gg1_field);
                    String current = question.getText();
                    if (current.length() > 0) question.setText(current.substring(0, current.length() - 1));
                }
            });//撤回

            this.findComponentById(ResourceTable.Id_jac_button).setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component v) {
                    Text q1 = (Text) DWZH1AbilitySlice.this.findComponentById(ResourceTable.Id_gg1_field);
                    Text q3 = (Text) DWZH1AbilitySlice.this.findComponentById(ResourceTable.Id_gg3_field);
                    Text q2 = (Text) DWZH1AbilitySlice.this.findComponentById(ResourceTable.Id_gg2_field);
                    Text q4 = (Text) DWZH1AbilitySlice.this.findComponentById(ResourceTable.Id_gg4_field);
                    if (DWZH1AbilitySlice.panduan == 1) {
                        q1.setText("原数值");
                        q2.setText("原数单位");
                        q3.setText("结果值");
                        q4.setText("结果单位");
                        DWZH1AbilitySlice.panduan = 4;
                    } else {
                        q1.setText("原数值");
                        q3.setText("结果值");
                        DWZH1AbilitySlice.panduan = 4;
                    }
                }
            });//清空
            this.findComponentById(ResourceTable.Id_jj1_button).setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component v) {
                    DWZH1AbilitySlice.dw1 = DWZH1AbilitySlice.this.dw;
                    Text que1 = (Text) DWZH1AbilitySlice.this.findComponentById(ResourceTable.Id_gg2_field);
                    if (DWZH1AbilitySlice.dw1 == -1) {
                        DWZH1AbilitySlice.dw1 = 1;
                        que1.setText(DWZH1AbilitySlice.this.stringTitle[DWZH1AbilitySlice.dw1]);
                    } else que1.setText(DWZH1AbilitySlice.this.stringTitle[DWZH1AbilitySlice.dw1]);
                    DWZH1AbilitySlice.panduan = 2;
                }
            });//gg1
            this.findComponentById(ResourceTable.Id_jj2_button).setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component v) {
                    DWZH1AbilitySlice.dw2 = DWZH1AbilitySlice.this.dw;
                    Text ans1 = (Text) DWZH1AbilitySlice.this.findComponentById(ResourceTable.Id_gg4_field);
                    if (DWZH1AbilitySlice.dw2 == -1) {
                        DWZH1AbilitySlice.dw2 = 1;
                        ans1.setText(DWZH1AbilitySlice.this.stringTitle[DWZH1AbilitySlice.dw2]);
                    } else ans1.setText(DWZH1AbilitySlice.this.stringTitle[DWZH1AbilitySlice.dw2]);
                    DWZH1AbilitySlice.panduan = 3;
                }
            });//gg3
            this.findComponentById(ResourceTable.Id_jcal_button).setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component v) {
                    Text a1 = (Text) DWZH1AbilitySlice.this.findComponentById(ResourceTable.Id_gg1_field);
                    Text a3 = (Text) DWZH1AbilitySlice.this.findComponentById(ResourceTable.Id_gg3_field);
                    for (int i = 0; i < a1.getText().length(); i++) {
                        String temp = a1.getText().substring(i, i + 1);
                        boolean flag = Pattern.matches("[\u4E00-\u9FA5]", temp);
                        if (flag) a3.setText("结果值");
                        else
                            a3.setText(DWZH1AbilitySlice.dwcal(String.valueOf(a1.getText())));
                    }
                    //TODO:自定义埋点开始，在工程合适位置插入埋点代码
                    PacMap pacMap = new PacMap();
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                    pacMap.putString("user_uuid", "[" + Preference_RW.uuid.toString() + "]");
                    pacMap.putString("dwlx", "[" + xinxi.getText() + "]");
                    Text ans1 = (Text) DWZH1AbilitySlice.this.findComponentById(ResourceTable.Id_gg4_field);
                    Text ans2 = (Text) DWZH1AbilitySlice.this.findComponentById(ResourceTable.Id_gg2_field);
                    pacMap.putString("start_num", "[" + a1.getText() + "],单位:(" + ans2.getText() + ")");
                    pacMap.putString("end_num", "[=" + a3.getText() + "],单位:(" + ans1.getText() + ")");
                    pacMap.putString("se_time", "[" + df.format(new Date()) + "]");
                    instance_hi.onEvent("dwhs", pacMap);
                    //TODO:埋点结束
                    DWZH1AbilitySlice.panduan = 1;
                }
            });//计算
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
    }

    /**
     * 展示数据
     *
     * @param text1 the text 1
     */
    private void ShowDialog(String text1) {
        try {
            ohos.data.distributed.device.DeviceInfo localDeviceInfo = KvManagerFactory.getInstance()
                    .createKvManager(new KvManagerConfig((this))).getLocalDeviceInfo();
            int localDeviceType = Integer.parseInt(localDeviceInfo.getType());
            if (localDeviceType == DeviceInfo.DeviceType.PHONE.value()) {
                new MyToastDialog(this.getContext(), text1, ResourceTable.Graphic_xtoast_framem, 36, 25)
                        .setDuration(120)
                        .setAlignment(LayoutAlignment.BOTTOM)
                        .setOffset(0, 100)
                        .show();
                XLog.info(label, "当前设备类型为手机");
            } else if (localDeviceType == DeviceInfo.DeviceType.TABLET.value()) {
                new MyToastDialog(this.getContext(), text1, ResourceTable.Graphic_xtoast_framet, 43, 37)
                        .setDuration(120)
                        .setAlignment(LayoutAlignment.BOTTOM)
                        .setOffset(0, 100)
                        .show();
                XLog.info(label, "当前设备类型为平板");
            } else {
                XLog.warn(label, "暂不支持您的设备:(" + localDeviceInfo.getType() + ")");
                this.terminateAbility();
            }
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
    }

    /**
     * 移动
     *
     * @param component  the component
     * @param touchEvent the touch event
     * @return boolean boolean
     */
    @Override
    public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
        try {
            int action = touchEvent.getAction();
            if (action == TouchEvent.PRIMARY_POINT_DOWN) {
                MmiPoint position = touchEvent.getPointerPosition(0);
                this.starx = position.getX();
                this.stary = position.getY();
            } else if (action == TouchEvent.PRIMARY_POINT_UP) {
                MmiPoint position = touchEvent.getPointerPosition(0);
                this.endx = position.getX();
                this.endy = position.getY();
                if (this.starx > this.endx && Math.abs(this.stary - this.endy) < 123 && Math.abs(this.starx - this.endx) > 156) {
                    /*无参--页面跳转开始*/
                    Intent intent = new Intent();
                    Operation operation = new Intent.OperationBuilder()
                            .withDeviceId("")
                            .withBundleName(this.getBundleName())
                            .withAbilityName("com.xcl.calculator.Ability.DanWeiCal.DWZH2Ability")
                            .build();// 通过Intent中的OperationBuilder类构造operation对象，指定设备标识（空串表示当前设备）、应用包名、Ability名称
                    intent.setOperation(operation);// 把operation设置到intent中
                    this.startAbility(intent);
                    this.onBackPressed();
                    /*页面跳转结束--无参*/
                    XLog.info(label, "左滑了");
                } else if (this.starx < this.endx && Math.abs(this.stary - this.endy) < 123 && Math.abs(this.starx - this.endx) > 156) {
                    /*无参--页面跳转开始*/
                    Intent intent = new Intent();
                    Operation operation = new Intent.OperationBuilder()
                            .withDeviceId("")
                            .withBundleName(this.getBundleName())
                            .withAbilityName("com.xcl.calculator.Ability.CaiDanAbility")
                            .build();// 通过Intent中的OperationBuilder类构造operation对象，指定设备标识（空串表示当前设备）、应用包名、Ability名称
                    intent.setOperation(operation);// 把operation设置到intent中
                    this.startAbility(intent);
                    this.onBackPressed();
                    /*页面跳转结束--无参*/
                    XLog.info(label, "右滑了");
                } else if (this.stary > this.endy && Math.abs(this.starx - this.endx) < 123 && Math.abs(this.stary - this.endy) > 156)
                    XLog.info(label, "上滑了");
                else if (this.stary < this.endy && Math.abs(this.starx - this.endx) < 123 && Math.abs(this.stary - this.endy) > 156)
                    XLog.info(label, "下滑了");
                else XLog.info(label, "无效滑动（请直一点！）");
            } else XLog.info(label, "滑动中");
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
        return true;
    }

    /**
     * 初始化数据
     */
    private void prepareButtons() {
        try {
            int[] direct_button = {
                    ResourceTable.Id_gnumber0_button,//0
                    ResourceTable.Id_gnumber1_button,//1
                    ResourceTable.Id_gnumber2_button,//2
                    ResourceTable.Id_gnumber3_button,//3
                    ResourceTable.Id_gnumber4_button,//4
                    ResourceTable.Id_gnumber5_button,//5
                    ResourceTable.Id_gnumber6_button,//6
                    ResourceTable.Id_gnumber7_button,//7
                    ResourceTable.Id_gnumber8_button,//8
                    ResourceTable.Id_gnumber9_button,//9
                    ResourceTable.Id_gnumberd_button,//.
            };
            for (int id : direct_button)
                this.findComponentById(id).setClickedListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component v) {
                        Text qqq = (Text) DWZH1AbilitySlice.this.findComponentById(ResourceTable.Id_gg1_field);
                        if (DWZH1AbilitySlice.panduan >= 0 && DWZH1AbilitySlice.panduan <= 4) {
                            qqq.setText(((Button) v).getText());
                            DWZH1AbilitySlice.panduan = 5;
                        } else qqq.setText(qqq.getText() + ((Button) v).getText());

                    }
                });
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
    }

    /**
     * 切换后台并销毁，防止手表抽风
     */
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        this.terminateAbility();
    }

    /**
     * 退出
     *
     * @param keyCode  the key code
     * @param keyEvent the key event
     * @return boolean boolean
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent keyEvent) {
        if (keyCode == KeyEvent.KEY_BACK) {
            this.ShowDialog("程序退出成功，感谢您的使用!");
            this.terminateAbility();
            return true;
        }
        return super.onKeyDown(keyCode, keyEvent);
    }
}
